import React, { useEffect, useMemo, useState } from 'react';
import { Form, Row, Spin, Card, Tabs, message } from 'antd';
import { isSuccess } from '@/utils/request';
import { connect } from 'umi';
import groupBy from 'lodash/groupBy';
import omit from 'lodash/omit';
import classnames from 'classnames';

import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { itemRecheckService } from '@/services/salaryManage/salaryCalculate';

import CheckHeader from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckHeader/itemIndex';
import CheckBody from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckBody/itemIndex';
import { ColumnProcessor, CommonColumnInterceptor } from '@/pages/SalaryManage/SalaryCalculate/Recheck/ColumnProcessor';
import {
    numberFilter,
    orFilter,
    summaryFieldChooser
} from '@/pages/SalaryManage/SalaryCalculate/Recheck/SummaryProcessor';

import { OrganizationNameHead } from '@/pages/SalaryManage/components/OrganizationName';

const { TabPane } = Tabs;
const rowKey = 'id';

const getGroupKey = item => item?.payrollId;

const RecheckSummaryChooser = summaryFieldChooser(
    orFilter(numberFilter, col => ({
        success: col.dataIndex === 'employeeBaseInfo',
        result: { [col.dataIndex]: '合计' }
    }))
);
const Index = ({ location, columnProcessor }) => {
    const [tableHeader, setTableHeader] = useState({});
    const [hoverRowData, setHoverRowData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10
    });
    const [pageData, setPageData] = useState({
        total: undefined,
        rows: []
    });
    const { parentId, organizationCode, employeeCode, leafSalaryItemId, period } = location.query;
    const [searchModel, setSearchModel] = useState({
        rootSalaryItemId: parentId,
        organizationCode,
        employeeCode,
        leafSalaryItemId,
        period
    });

    // 初始化
    useEffect(() => {
        const init = async () => {
            const {
                period: periodStr = '',
                rootSalaryItemId,
                leafSalaryItemId: itemId,
                organizationCode: orgCode,
                ...postParam
            } = searchModel;
            const year = periodStr.substr(0, 4);
            const month = periodStr.substr(5);
            setLoading(true);
            const [headerRes, tableRes] = await Promise.all([
                itemRecheckService.queryTableHeadData({
                    year,
                    month,
                    parentId: rootSalaryItemId,
                    leafSalaryItemId: itemId,
                    organizationCode: orgCode
                }),
                itemRecheckService.queryTableBodyData({
                    year,
                    month,
                    rootSalaryItemId,
                    leafSalaryItemId: itemId,
                    organizationCode: orgCode,
                    page: {
                        pageNo: pagination.current,
                        pageSize: pagination.pageSize
                    },
                    ...postParam
                })
            ]);

            setLoading(false);
            if (isSuccess(headerRes)) {
                setTableHeader(headerRes.data);
            } else {
                message.error(headerRes.msg);
            }

            if (isSuccess(tableRes)) {
                setPageData({
                    ...tableRes.data
                });
            } else {
                message.error(tableRes.msg);
            }
        };
        if (searchModel.organizationCode) {
            init();
        }
    }, [searchModel, pagination]);

    const employeeBaseInfo = useMemo(
        () => tableHeader?.tableHeaderItemList?.find(item => item.dataIndex === 'employeeBaseInfo'),
        [tableHeader]
    );
    const employeeFieldTitleArray = useMemo(
        () => (employeeBaseInfo?.children || []).map(it => [it.title, it.dataIndex]),
        [employeeBaseInfo]
    );
    const bridgeTableHeader = useMemo(
        () =>
            tableHeader.tableHeaderItemList?.map(item =>
                // 如果是用户信息则去掉children
                item.dataIndex === 'employeeBaseInfo' ? omit(item, 'children') : { ...item }
            ),
        [tableHeader.tableHeaderItemList]
    );
    const bridgeDataSource = useMemo(() => {
        let result = [];
        let index = 0;

        // eslint-disable-next-line no-unused-expressions
        pageData.rows?.forEach(item => {
            const employeeInfoMap = employeeFieldTitleArray.map(it => ({
                labelName: it[0],
                labelValue: item[it[1]]
            }));
            result = result.concat(
                (item.payrollItemList || []).map(it => {
                    index += 1;
                    return {
                        id: `${getGroupKey(item)}_${index}`,
                        employeeBaseInfo: employeeInfoMap,
                        ...omit(item, 'payrollItemList'),
                        ...it,
                        ...item,
                        ...it.attendData
                    };
                })
            );
        });
        return result;
    }, [pageData.rows, employeeFieldTitleArray]);

    const memoDataSource = useMemo(() => {
        const allData = [].concat(bridgeDataSource);
        const employeeGroup = groupBy(allData, getGroupKey);

        return allData.map((item, index, arr) => {
            const preItem = index === 0 ? null : arr[index - 1];

            return {
                ...item,
                _rowSpan: getGroupKey(preItem) !== getGroupKey(item) ? employeeGroup[getGroupKey(item)].length : 0
            };
        });
    }, [bridgeDataSource]);

    const tableProps = {
        onRow: record => ({
            className: classnames({
                'row-hover': hoverRowData && getGroupKey(hoverRowData) === getGroupKey(record)
            }),
            onMouseEnter: () => {
                setHoverRowData(record);
            },
            onMouseLeave: () => {
                setHoverRowData([]);
            }
        })
    };

    const changePageHandle = ({ current, pageSize }) => {
        setPagination({
            ...pagination,
            pageSize,
            current
        });
    };

    return (
        <PageHeaderWrapper>
            <Card style={{ padding: 9 }}>
                <Tabs
                    defaultActiveKey="1"
                    style={{ marginTop: '-15px' }}
                    tabBarExtraContent={
                        <div style={{ lineHeight: '44px' }}>
                            <OrganizationNameHead organizationCode={organizationCode} />
                        </div>
                    }
                >
                    <TabPane tab={tableHeader.dynamicQueryName || ' '} key="1" style={{ marginTop: '-15px' }}>
                        <Spin spinning={loading}>
                            <CheckHeader
                                period={searchModel.period}
                                checkButtonList={[]}
                                dynamicQueryConditionsMapList={tableHeader.dynamicQueryConditionsMapList}
                                dynamicQueryName={tableHeader.dynamicQueryName}
                                searchModel={searchModel}
                                setSearchModel={setSearchModel}
                            />
                            <CheckBody
                                rowKey={rowKey}
                                tableHeader={bridgeTableHeader}
                                columnProcessor={columnProcessor}
                                jumpItem={false}
                                summaryFields={RecheckSummaryChooser}
                                changePage={changePageHandle}
                                dataSource={memoDataSource}
                                pagination={{
                                    ...pagination,
                                    total: pageData.total
                                }}
                                loading={loading}
                                hideSelection
                                tableProps={tableProps}
                            />
                        </Spin>
                    </TabPane>
                </Tabs>
            </Card>
        </PageHeaderWrapper>
    );
};

const columnProcessor = new ColumnProcessor(
    {
        employeeBaseInfo: {
            fixed: true,
            width: 220,
            render(text, record) {
                return {
                    children: !record?.$$isSummary ? (
                        <div>
                            {Array.isArray(record.employeeBaseInfo) &&
                                record.employeeBaseInfo.map(({ labelName, labelValue }) => (
                                    //
                                    <Row key={labelName} style={{ whiteSpace: 'normal', wordBreak: 'break-all' }}>
                                        <span>{labelName}：</span>
                                        <span>{labelValue}</span>
                                    </Row>
                                ))}
                        </div>
                    ) : (
                        text
                    ),
                    props: {
                        // eslint-disable-next-line no-underscore-dangle
                        rowSpan: record._rowSpan
                    }
                };
            }
        }
    },
    CommonColumnInterceptor,
    null
);

const PerformancePayWithForm = Form.create({ name: 'PerformancePayWithForm' })(Index);
export default withRoutePage(
    connect(() => ({
        columnProcessor
    }))(PerformancePayWithForm)
);
